package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.AppointSchoolMapper;
import com.xmy.cultivate.mapper.RoleAdminMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 员工 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

    @Autowired
    IQyWacherService iQyWacherService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IAdminService iAdminService;

    @Autowired
    IAppointSchoolService iAppointSchoolService;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IRoleAdminService iRoleAdminService;

    @Autowired
    IOrganizationStaffService iOrganizationStaffService;


    @Autowired
    AppointSchoolMapper appointSchoolMapper;

    @Autowired
    RoleAdminMapper roleAdminMapper;

    @Autowired
    IDictService iDictService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    ITeacherLeadsYearClassService iTeacherLeadsYearClassService;

    @Autowired
    IStudentAccountService iStudentAccountService;

    @Autowired
    IQuarterService iQuarterService;

    @Override
    @Transactional
    public boolean saveTo(Staff staff) {
        Long adminId = idWorker.nextId();
        if (staff.getId()!= null){
            adminId = staff.getId();
        }

        Admin admin = staff.getAdminObj();
        if (admin.getAccount() != null && !admin.getAccount().isEmpty()) {
            String account = admin.getAccount();
            long count = iAdminService.count(new QueryWrapper<Admin>().eq("account", account));
            if (count > 0) {
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(adminId);
            //boolean rs = CommonUtil.isPasswordAvailable("",admin.getPwd());
            //if (!rs){
            //throw new CommonException(ResultCode.PWD_EASY);
            //}

            String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);

            //机构账号，管辖校区
            /*List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item : admin.getSchoolIdList()) {
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(adminId);
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //机构账号，角色
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item : admin.getRoleIdList()) {
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(adminId);
                roleAdminList.add(roleAdmin);
            }

            if (!appointSchoolList.isEmpty()) {
                iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            }
            if (!roleAdminList.isEmpty()) {
                iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            }*/
        }

        staff.setId(adminId);
        staff.setAdminId(adminId);

        //所属部门
        List<OrganizationStaff> organizationStaffList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        for (Long id : staff.getDepartIdList()) {
            OrganizationStaff organizationStaff = new OrganizationStaff();
            organizationStaff.setOrganizationId(id);
            organizationStaff.setStaffId(staff.getId());
            organizationStaffList.add(organizationStaff);
        }

        for (Long id : staff.getScopeSchoolIdList()) {
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(4);
            scopeSchoolList.add(appointSchool);
        }

        Long id = staff.getId();
        //删除老师带班年级
        QueryWrapper<TeacherLeadsYearClass> teacherLeadsYearClassQueryWrapper = new QueryWrapper<>();
        teacherLeadsYearClassQueryWrapper.eq("teacher_id", id);
        iTeacherLeadsYearClassService.remove(teacherLeadsYearClassQueryWrapper);
        List<TeacherLeadsYearClass> teacherLeadsYearClassIdList = new ArrayList<>();
        Integer yearClassId = 0;
        for (Integer item : staff.getTeacherLeadsYearClassIdList()){
            TeacherLeadsYearClass teacherLeadsYearClass = new TeacherLeadsYearClass();
            teacherLeadsYearClass.setTeacherId(id);
            teacherLeadsYearClass.setYearClassId(item);
            teacherLeadsYearClassIdList.add(teacherLeadsYearClass);
            yearClassId = item;
        }
        if (teacherLeadsYearClassIdList.size() > 0) {
            iTeacherLeadsYearClassService.saveBatch(teacherLeadsYearClassIdList, teacherLeadsYearClassIdList.size());
        }

        if (!organizationStaffList.isEmpty()) {
            //iOrganizationStaffService.saveBatch(organizationStaffList, organizationStaffList.size());
        }
        if (!scopeSchoolList.isEmpty()) {
            //iAppointSchoolService.saveBatch(scopeSchoolList, scopeSchoolList.size());
        }

        this.save(staff);

        Student student = new Student();
        student.setId(staff.getId());
        student.setName(staff.getName());
        student.setLinkmanPhone(staff.getPhone());
        student.setLinkman(staff.getName());
        student.setSchoolId(staff.getSchoolId());
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        TypeValueData typeValueData = new TypeValueData();
        typeValueData.setTypeId(3);
        typeValueData.setContent(staff.getPhone());
        typeValueDataList.add(typeValueData);
        student.setLinkManList(typeValueDataList);
        student.setGradeId(yearClassId);
        student.setYearClassId(yearClassId);
        iStudentService.addOrUpdateData(student);

        // 获取当前年份学期
        Quarter nowQuarter = iQuarterService.getNowQuarter();
        if (staff.getSiginSubjects() != null) {
            String[] siginSubjects = staff.getSiginSubjects().split(",");
            for (String subjectId : siginSubjects) {
                iStudentAccountService.addStudentAccountBatch(nowQuarter.getYearPart(), nowQuarter.getNum(), staff.getId(), Long.valueOf(subjectId));
            }
        }

        if (staff.getPhone().length() == 11){
            //电话号码如果变了，更新企业微信号
            //iMqPushService.updateQyWecharId(staff);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean updateTo(Staff staff) {
        Admin admin = staff.getAdminObj();
        Long adminId = staff.getId();

        Staff staffOld = this.getById(staff.getId());
        if (!Objects.isNull(staffOld)){
            if (staffOld.getPhone() != staff.getPhone()){
                if (staff.getPhone().length() == 11){
                    //电话号码如果变了，更新企业微信号
                    //iMqPushService.updateQyWecharId(staff);
                }
            }
        }

        /*if (staff.getStatus().equals(StatusStaffEnum.OUT)) {
            staff.setLeaveDate(LocalDate.now());
        } else{
            staff.setLeaveDate(null);
        }*/

        if (admin != null && admin.getId() != null) {
            String account = admin.getAccount();
            Admin adminOld = iAdminService.getById(staff.getId());

            admin.setId(staff.getId());
            if (StringUtils.isNotBlank(admin.getPwd())) {
                admin.setPwdShow(admin.getPwd());
                String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
                admin.setPwd(pwd);
            }else {
                if (Objects.nonNull(adminOld)){
                    admin.setPwd(adminOld.getPwd());
                }
            }

            Long id = staff.getId();
            //删除老师带班年级
            QueryWrapper<TeacherLeadsYearClass> teacherLeadsYearClassQueryWrapper = new QueryWrapper<>();
            teacherLeadsYearClassQueryWrapper.eq("teacher_id", id);
            iTeacherLeadsYearClassService.remove(teacherLeadsYearClassQueryWrapper);
            List<TeacherLeadsYearClass> teacherLeadsYearClassIdList = new ArrayList<>();
            for (Integer item : staff.getTeacherLeadsYearClassIdList()){
                TeacherLeadsYearClass teacherLeadsYearClass = new TeacherLeadsYearClass();
                teacherLeadsYearClass.setTeacherId(id);
                teacherLeadsYearClass.setYearClassId(item);
                teacherLeadsYearClassIdList.add(teacherLeadsYearClass);
            }
            if (teacherLeadsYearClassIdList.size() > 0) {
                iTeacherLeadsYearClassService.saveBatch(teacherLeadsYearClassIdList, teacherLeadsYearClassIdList.size());
            }

            //iAdminService.updateById(admin);

            iAdminService.saveOrUpdate(admin);
            //先删除指定校区
            //QueryWrapper<AppointSchool> delAppointSchoolQueryWrapper = new QueryWrapper<>();
            //delAppointSchoolQueryWrapper.eq("for_id", admin.getId()).eq("type", 2);
            //appointSchoolMapper.delete(delAppointSchoolQueryWrapper);

            if (admin.getGovernMode().equals(3)){
                //所属校区
                //List<Long> schoolIdList = new ArrayList<>();
                //schoolIdList.add(staff.getSchoolId());
                //admin.setSchoolIdList(schoolIdList);
            }
            //List<AppointSchool> appointSchoolList = new ArrayList<>();
            //for (Long item : admin.getSchoolIdList()) {
                //AppointSchool appointSchool = new AppointSchool();
                //appointSchool.setForId(staff.getId());
                //appointSchool.setSchoolId(item);
                //appointSchool.setType(2);//机构帐号指定校区
                //appointSchoolList.add(appointSchool);
            //}
            //先删除角色
            /*QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
            roleAdminQueryWrapper.eq("admin_id", admin.getId());
            roleAdminMapper.delete(roleAdminQueryWrapper);
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item : admin.getRoleIdList()) {
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(admin.getId());
                roleAdminList.add(roleAdmin);
            }
            if (appointSchoolList.size() > 0) {
                iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            }
            if (roleAdminList.size() > 0) {
                iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            }*/
        } else  if (admin != null){
            String account = admin.getAccount();
            if (StringUtils.isNotBlank(account)) {
                Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account", account));
                if (count > 0) {
                    throw new CommonException(ResultCode.ACCOUNT_IN);
                    //throw new CommonException(ResultCode.quarterNo);
                }
            }

            admin.setId(adminId);
            staff.setAdminId(adminId);
            //boolean rs = CommonUtil.isPasswordAvailable("",admin.getPwd());
            //if (!rs){
            //throw new CommonException(ResultCode.PWD_EASY);
            //}
            String pwd = new Md5Hash(admin.getPwd(), admin.getAccount(), 3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);
            if (admin.getGovernMode().equals(3)){
                //所属校区
                //List<Long> schoolIdList = new ArrayList<>();
                //schoolIdList.add(staff.getSchoolId());
                //admin.setSchoolIdList(schoolIdList);
            }

            //机构账号，管辖校区
            //List<AppointSchool> appointSchoolList = new ArrayList<>();
            //for (Long item : admin.getSchoolIdList()) {
                //AppointSchool appointSchool = new AppointSchool();
                //appointSchool.setForId(adminId);
                //appointSchool.setSchoolId(item);
                //appointSchool.setType(2);//机构帐号指定校区
                //appointSchoolList.add(appointSchool);
            //}
            //机构账号，角色
            //List<RoleAdmin> roleAdminList = new ArrayList<>();
            //for (Long item : admin.getRoleIdList()) {
            //    RoleAdmin roleAdmin = new RoleAdmin();
            //    roleAdmin.setRoleId(item);
            //    roleAdmin.setAdminId(adminId);
            //    roleAdminList.add(roleAdmin);
            //}

            //if (appointSchoolList.size() > 0) {
            //    iAppointSchoolService.saveBatch(appointSchoolList, appointSchoolList.size());
            //}
            //if (roleAdminList.size() > 0) {
            //    iRoleAdminService.saveBatch(roleAdminList, roleAdminList.size());
            //}
        }

        //所属部门(需求变动，不需要此功能)
        //List<OrganizationStaff> organizationStaffList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        /*for (Long id : staff.getDepartIdList()) {
            OrganizationStaff organizationStaff = new OrganizationStaff();
            organizationStaff.setOrganizationId(id);
            organizationStaff.setStaffId(staff.getId());
            organizationStaffList.add(organizationStaff);
        }*/

//        if (staff.getScopeSchoolIdList() != null) {
//            for (Long id : staff.getScopeSchoolIdList()) {
//                AppointSchool appointSchool = new AppointSchool();
//                appointSchool.setSchoolId(id);
//                appointSchool.setForId(staff.getId());
//                appointSchool.setType(4);
//                scopeSchoolList.add(appointSchool);
//            }
//        }
        //先删除部门
        /*iOrganizationStaffService.remove(new QueryWrapper<OrganizationStaff>().eq("staff_id", staff.getId()));
        if (organizationStaffList.size() > 0) {
            iOrganizationStaffService.saveBatch(organizationStaffList, organizationStaffList.size());
        }*/

        //先删除上课校区范围指定校区
//        iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id", staff.getId()).eq("type", 4));
//        if (scopeSchoolList.size() > 0) {
//            iAppointSchoolService.saveBatch(scopeSchoolList, scopeSchoolList.size());
//        }
        //staff.setId(adminId);

        Dict dict = iDictService.getDictByNumAndType(staff.getCourseInId(), 20);
        if (dict != null) {
            staff.setCourseInMoney(dict.getMoney());
            staff.setCourseInCount(dict.getCount());
        }
        this.saveOrUpdate(staff);

        Student student = iStudentService.getById(staff.getId());
        if (Objects.isNull(student)){
            student = new Student();
            Integer yearClassId = 0;
            for (Integer item : staff.getTeacherLeadsYearClassIdList()){
                yearClassId = item;
            }
            student.setId(staff.getId());
            student.setName(staff.getName());
            student.setLinkmanPhone(staff.getPhone());
            student.setLinkman(staff.getName());
            student.setSchoolId(staff.getSchoolId());
            List<TypeValueData> typeValueDataList = new ArrayList<>();
            TypeValueData typeValueData = new TypeValueData();
            typeValueData.setTypeId(3);
            typeValueData.setContent(staff.getPhone());
            typeValueDataList.add(typeValueData);
            student.setLinkManList(typeValueDataList);
            student.setGradeId(yearClassId);
            student.setYearClassId(yearClassId);
            iStudentService.addOrUpdateData(student);
        }

        // 获取当前年份学期
        Quarter nowQuarter = iQuarterService.getNowQuarter();
        if (staff.getSiginSubjects() != null) {
            String[] siginSubjects = staff.getSiginSubjects().split(",");
            for (String subjectId : siginSubjects) {
                iStudentAccountService.addStudentAccountBatch(nowQuarter.getYearPart(), nowQuarter.getNum(), staff.getId(), Long.valueOf(subjectId));
            }
        }

        return true;
    }

    @Override
    public boolean updateQyWecharId(Staff staff) throws WxErrorException {
        String qyWecharId =  iQyWacherService.getUserId(staff.getPhone());
        if (StringUtils.isNotBlank(qyWecharId)) {
            Staff updateStaff = new Staff();
            updateStaff.setId(staff.getId());
            updateStaff.setQyWecharId(qyWecharId);
            this.updateById(updateStaff);
        }
        return true;
    }
}
